import 'package:flutter/material.dart';
import 'package:wallet_utils/log_util.dart';
import 'dart:io';

import 'package:path_provider/path_provider.dart';

class CacheClearUtils{

  static Future<bool> clearTotalCache(BuildContext context) async {
    try {
      Directory tempDir = await getTemporaryDirectory();
      ///删除缓存目录
      await delDir(tempDir).then((bool){
        return true;
      });
      return false;
    } catch (e) {
      LogUtils.d(e);
      return false;
    } finally {
    }
  }


  static Future<bool> delDir(FileSystemEntity file) async {
    try {
      if (file is Directory) {
        final List<FileSystemEntity> children = file.listSync();
        for (final FileSystemEntity child in children) {
          await delDir(child);
        }
      }
      await file.delete();
      return true;
    } catch (e) {
      LogUtils.d(e);
      return false;
    }
  }

  static Future<double> getTotalSizeOfFilesInDir(
      final FileSystemEntity file) async {
    try {
      if (file is File) {
        int length = await file.length();
        return double.parse(length.toString());
      }
      if (file is Directory) {
        final List<FileSystemEntity> children = file.listSync();
        double total = 0;
        for (final FileSystemEntity child in children) {
          total += await getTotalSizeOfFilesInDir(child);
        }
        return total;
      }
      return 0;
    } catch (e) {
      LogUtils.d(e);
      return 0;
    }
  }

  static renderSize(double value) {
    if (null == value) {
      return 0;
    }
    List<String> unitArr = []..add('B')..add('K')..add('M')..add('G');
    int index = 0;
    while (value > 1024) {
      index++;
      value = value / 1024;
    }
    String size = index>0?value.toStringAsFixed(2):value.toStringAsFixed(0);
    return size + unitArr[index];
  }

  static Future<String> loadTemporaryDirectory() async {
    try {
      Directory tempDir = await getTemporaryDirectory();
      double value = await getTotalSizeOfFilesInDir(tempDir);
      return renderSize(value);
    } catch (err) {
      LogUtils.d(err);
    }
    return '';
  }
}